package com.wanpinghui.wphlibrary.model.db.manager;

import com.wanpinghui.wphlibrary.WPHLibrary;
import com.wanpinghui.wphlibrary.model.oauth.UserInfoUtil;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductFormatBean;
import com.yunshl.yunshllibrary.storage.MDBManager;

import org.xutils.common.util.KeyValue;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;

import java.util.List;

import retrofit.callback.FailOrExceptionType;
import retrofit.callback.YRequestCallback;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.observables.AsyncOnSubscribe;
import rx.observables.SyncOnSubscribe;
import rx.schedulers.Schedulers;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/12/22
 ***/

public class CartDbManager {
    private UserBean userBean;
    private static CartDbManager instance;

    public static CartDbManager getInstance() {
        if (instance == null) {
            instance = new CartDbManager();
        }
        return instance;
    }

    public CartDbManager(){
        userBean = UserInfoUtil.getUserInfo();
    }


    /**
     * 增加到购物车（数量覆盖）
     * @param productBean
     * @param bean
     * @return
     */
    public void addToCart(final ProductBean productBean, final ProductFormatBean bean) {
        if (userBean == null) {
            userBean = UserInfoUtil.getUserInfo();
        }
        if (userBean == null || productBean == null || bean == null) {
            return ;
        }
        Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                try {
                    MDBManager.getInstance().getDbManager(userBean.getUser().getId()).saveOrUpdate(productBean);
                    MDBManager.getInstance().getDbManager(userBean.getUser().getId()).saveOrUpdate(bean);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                int count = getCartProductCount();
                subscriber.onNext(count);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                WPHLibrary.getLibrary().onCartChange(integer);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }

    /**
     * 增加到购物车（数量增加）
     * @param productBean
     * @param list
     * @return
     */
    public void addToCart2(final ProductBean productBean, final List<ProductFormatBean> list) {
        if (userBean == null) {
            userBean = UserInfoUtil.getUserInfo();
        }
        if (userBean == null || productBean == null || list == null) {
            return;
        }

        Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                try {
                    MDBManager.getInstance().getDbManager(userBean.getUser().getId()).saveOrUpdate(productBean);
                    if (list != null && list.size() > 0) {
                        for (ProductFormatBean bean : list) {
                            if (bean.getCount() > 0) {
                                MDBManager.getInstance().getDbManager(userBean.getUser().getId()).saveOrUpdate(bean);
                            }else {
                                MDBManager.getInstance().getDbManager(userBean.getUser().getId()).deleteById(ProductFormatBean.class, bean.getId());
                            }
                        }
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
                int count = getCartProductCount();
                subscriber.onNext(count);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                WPHLibrary.getLibrary().onCartChange(integer);
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }

    public int getCartProductCount() {
        if (userBean == null) {
            userBean = UserInfoUtil.getUserInfo();
        }
        if (userBean == null) {
            return 0;
        }
        int count = 0;
        try {
            List<ProductFormatBean> list = MDBManager.getInstance().getDbManager(userBean.getUser().getId()).findAll(ProductFormatBean.class);
            if (list != null && list.size() > 0) {
                for (ProductFormatBean formatBean : list) {
                    count = count + formatBean.getCount();
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return count;
    }

    public int getCartProductCount(int formatId) {
        if (userBean == null) {
            userBean = UserInfoUtil.getUserInfo();
        }
        if (userBean == null) {
            return 0;
        }
        int count = 0;
        try {
            ProductFormatBean formatBean = MDBManager.getInstance().getDbManager(userBean.getUser().getId())
                    .findById(ProductFormatBean.class, formatId);
            if (formatBean != null) {
                count = count + formatBean.getCount();
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        return count;
    }

    public void getCartProduct(final YRequestCallback<List<ProductBean>> callback) {
        if (userBean == null) {
            userBean = UserInfoUtil.getUserInfo();
        }
        if (userBean == null) {
            if (callback != null) {
                callback.onFailed(0, "用户未登录");
                WPHLibrary.getLibrary().sendRequestFial(FailOrExceptionType.NO_LOGIN,401);
            }
        }
        Observable.create(new Observable.OnSubscribe<List<ProductBean>>() {
            @Override
            public void call(Subscriber<? super List<ProductBean>> subscriber) {
                try {
                    List<ProductBean> list = MDBManager.getInstance().getDbManager(userBean.getUser().getId()).findAll(ProductBean.class);
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size();) {
                            ProductBean productBean = list.get(i);
                            List<ProductFormatBean> formatBeanList = MDBManager.getInstance().getDbManager(userBean.getUser().getId())
                                    .selector(ProductFormatBean.class)
                                    .where("parent_id","=",productBean.getId()).findAll();
                            if (formatBeanList != null && formatBeanList.size() > 0) {
                                productBean.setFormatList(formatBeanList);
                                i++;
                            }else {
                                list.remove(productBean);
                                MDBManager.getInstance().getDbManager(userBean.getUser().getId()).deleteById(ProductBean.class,productBean.getId());
                            }
                        }
                    }
                    subscriber.onNext(list);
                } catch (DbException e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<ProductBean>>() {
                    @Override
                    public void call(List<ProductBean> productBeans) {
                        if (callback != null) {
                            callback.onSuccess(productBeans);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                        if (callback != null) {
                            callback.onFailed(0, throwable.getMessage());
                        }
                    }
                });
    }

    public void setFormatCount(final int formatId, final int count) {
        if (userBean == null) {
            userBean = UserInfoUtil.getUserInfo();
        }
        if (userBean == null) {
            return ;
        }
        Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                try {
                    MDBManager.getInstance().getDbManager(userBean.getUser().getId())
                            .update(ProductFormatBean.class, WhereBuilder.b("id","=",formatId), new KeyValue("count",count));
                    int count = getCartProductCount();
                    subscriber.onNext(count);
                } catch (DbException e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer count) {
                        WPHLibrary.getLibrary().onCartChange(count);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                });
    }

}
